/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.inventory;

import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import main.ServicesList;
import model.inventory.Dept;
import org.apache.log4j.Logger;
import utility.Constants;
import utility.com.treeTable.*;
import view.RekapTemplate;

/**
 *
 * @author Yusup Jauhari Shandi <in.visi>
 */
public class DeptListFrm extends RekapTemplate {

    /**
     * Creates new form DeptListFrm
     */
    
    private DeptNode selectedNode;
    private TreeTable myTreeTable;
    private static Logger log = Logger.getLogger(DeptListFrm.class);
    public DeptListFrm() {
        initComponents();
        
        loadData();
                
          //rootNodes.add(new DeptNodegetDeptService(5, "02", "DEPT", 1, 2, null));
               
        
        
        
    }

    private void treeSelection(TreeSelectionEvent evt){
        JOptionPane.showMessageDialog(this, "here");
    }
    
     private List<DeptNode> createDataStructure(int induk) {
//          List<DeptNode> children1 = new ArrayList<>();
//        children1.add(new DeptNode(2, "00", "FOOD", 1, 2, null));
//        children1.add(new DeptNode(3, "00", "NON FOOD", 1, 2, null));
// 
//        List<DeptNode> children2 = new ArrayList<>();
         
        List<Dept> tree = ServicesList.getDeptService().getDeptTree(induk);
        if (tree.isEmpty()) {
            return null;
        }else {
            List<DeptNode> rootNodes = null;
            if (tree!=null){
                rootNodes = new ArrayList<>();
                for (Dept dept : tree){
                    rootNodes.add(new DeptNode(dept.getId(),dept.getKode(), dept.getNama(),dept.getInduk(), dept.getTinkat(), createDataStructure(dept.getId())));            
                }
            }  
            return rootNodes;
         }    
     }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        btnAdd = new javax.swing.JButton();
        btnSave = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnLoad = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txtKode = new javax.swing.JTextField();
        txtNama = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtIndukNama = new javax.swing.JTextField();
        txtInduk = new javax.swing.JTextField();
        txtId = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);
        jToolBar1.setMaximumSize(new java.awt.Dimension(32767, 20));
        jToolBar1.setSize(this.getWidth(), 50);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_add.png"))); // NOI18N
        btnAdd.setText("Tambah");
        btnAdd.setFocusable(false);
        btnAdd.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnAdd.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        jToolBar1.add(btnAdd);

        btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/filesave.png"))); // NOI18N
        btnSave.setText("Simpan");
        btnSave.setFocusable(false);
        btnSave.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveActionPerformed(evt);
            }
        });
        jToolBar1.add(btnSave);

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/edit_remove.png"))); // NOI18N
        btnDelete.setText("Hapus");
        btnDelete.setFocusable(false);
        btnDelete.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnDelete.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });
        jToolBar1.add(btnDelete);

        btnLoad.setIcon(new javax.swing.ImageIcon(getClass().getResource("/reload.png"))); // NOI18N
        btnLoad.setText("Load");
        btnLoad.setFocusable(false);
        btnLoad.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnLoad.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnLoad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoadActionPerformed(evt);
            }
        });
        jToolBar1.add(btnLoad);

        btnPrint.setIcon(new javax.swing.ImageIcon(getClass().getResource("/print.png"))); // NOI18N
        btnPrint.setText("Print");
        btnPrint.setFocusable(false);
        btnPrint.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnPrint.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar1.add(btnPrint);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setPreferredSize(new java.awt.Dimension(14, 50));

        jLabel1.setText("Kode :");

        jLabel2.setText("Nama :");

        jLabel3.setText("Induk :");

        txtIndukNama.setEnabled(false);

        txtInduk.setEnabled(false);

        txtId.setEnabled(false);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(txtKode, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtIndukNama))
                    .addComponent(txtNama, javax.swing.GroupLayout.PREFERRED_SIZE, 279, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtInduk, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtKode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(txtIndukNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtInduk, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtNama, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        // TODO add your handling code here:
        //new HadiahFrm().execute(0);
        initForm();
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
        // TODO add your handling code here:
        //updateGrid();
        validasi();
    }//GEN-LAST:event_btnSaveActionPerformed

    private void btnLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoadActionPerformed
        // TODO add your handling code here:
        loadData();
    }//GEN-LAST:event_btnLoadActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        // TODO add your handling code here:
        int rs = JOptionPane.showConfirmDialog(null, "Apakah data akan dihapus?", "Konfirmasi", JOptionPane.OK_CANCEL_OPTION);
        if (rs==0){
            int posisi = myTreeTable.getSelectedRow();
         int id = Integer.valueOf(myTreeTable.getModel().getValueAt(posisi, 4).toString());
         Dept node = ServicesList.getDeptService().getDept(id); 
            if (ServicesList.getDeptService().delete(node)){
                JOptionPane.showMessageDialog(null, "Data telah dihapus.");
                initForm();
                loadData();
            }   
            else {
                JOptionPane.showMessageDialog(null, "Data gagal dihapus.");
            }
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

     @Override
    public void execute(boolean withVisible, int id) {
       initGrid();
         if (withVisible) {
            setVisible(true);
        }
    }

    @Override
    protected void initGrid() {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected void initFilter() {
        //throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected void loadData() {
       DeptNode root = new DeptNode(0, "ROOT", "ROOT", 0, 0, createDataStructure(0));
        AbstractTreeTableModel treeTableModel = new DeptTM(root);
 
        myTreeTable = new TreeTable(treeTableModel);
        myTreeTable.setTreeSelectionListener(new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent ev) {
                //JOptionPane.showMessageDialog(null, "here");
                initForm();
                int posisi = myTreeTable.getSelectedRow();
                int id = Integer.valueOf(myTreeTable.getModel().getValueAt(posisi, 4).toString());
                Dept node = ServicesList.getDeptService().getDept(id);
                if (node!=null){
                    txtKode.setText(node.getKode());
                    txtNama.setText(node.getNama());
                    txtId.setText(String.valueOf(node.getId()));                        
                    
                    Dept induk = ServicesList.getDeptService().getDept(node.getInduk());
                    if (induk!=null){
                        txtIndukNama.setText(induk.getNama());
                        txtInduk.setText(String.valueOf(node.getInduk()));                        
                    }
                }
                
                
            }
        });
        jScrollPane1.setViewportView(myTreeTable);
    }

    @Override
    protected void updateGrid() {
      //  throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    protected void insertGrid() {
      //  throw new UnsupportedOperationException("Not supported yet.");
    }

    public DeptNode getSelectedNode() {
        selectedNode = (DeptNode)myTreeTable.getSelectionModel();
        return selectedNode;
    }
    
    
    private void initForm(){
        //TreeModel treeModel = myTreeTable.getTreeModel();
        
     //   selectedNode = (DeptNode)myTreeTable.getTree().getSelectionModel().getClass();
         int posisi = myTreeTable.getSelectedRow();
         int id = Integer.valueOf(myTreeTable.getModel().getValueAt(posisi, 2).toString());
         Dept node = ServicesList.getDeptService().getDept(id);
        txtKode.setText("");
        txtNama.setText("");
        txtId.setText("");
        
        if (node!=null){
            txtIndukNama.setText(node.getNama());
            txtInduk.setText(String.valueOf(node.getId()));
        }else{
            txtInduk.setText("0");
            txtIndukNama.setText("ROOT");
        }
            
    }
    
    private void validasi(){
        boolean valid;
        valid = txtKode.getText().equals("") ? false:true;
        StringBuilder msg = new StringBuilder();
        msg.append("Kode Belum diisi");
        if (valid){
            valid = txtNama.getText().equals("") ? false:true;            
            msg.setLength(0);
            msg.append("Nama belum diisi");
        }
        if (valid){
            save();
        }
        else{
            JOptionPane.showMessageDialog(this, msg.toString()
            ,"Warning",JOptionPane.WARNING_MESSAGE);
        }
    }
    
    private void save(){
        Dept dept = new Dept();
        //if (txtInduk.getText().equals("")){
            //dept.setInduk(Integer.parseInt(txtInduk.getText()));
            dept.setInduk(0);
        //}
        if (!txtId.getText().equals("")) {
            dept.setId(Integer.parseInt(txtId.getText()));
        }   
        dept.setKode(txtKode.getText());
        dept.setNama(txtNama.getText());
        dept.setTinkat(Constants.MASTER_ITEM_DEPTEMENT);
        boolean saved = false;
        try{
            saved = ServicesList.getDeptService().save(dept);
            loadData();
        } catch(Exception ex){
            log.error(ex);
            JOptionPane.showMessageDialog(this, "Data gagal disimpan."
            ,"Error",JOptionPane.ERROR_MESSAGE);
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DeptListFrm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnLoad;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField txtId;
    private javax.swing.JTextField txtInduk;
    private javax.swing.JTextField txtIndukNama;
    private javax.swing.JTextField txtKode;
    private javax.swing.JTextField txtNama;
    // End of variables declaration//GEN-END:variables

   
}
